<template>
  <div class="product-reviews">
    <div class="reviews-header">
      <h3>商品评价</h3>
      <div class="reviews-stats" v-if="statistics">
        <span class="total-reviews">共 {{ statistics.totalReviews }} 条评价</span>
        <span class="average-rating">
          <el-rate 
            v-model="statistics.averageRating" 
            disabled 
            show-score 
            text-color="#ff9900"
            score-template="{value}分"
          />
        </span>
      </div>
    </div>

    <!-- 评分筛选 -->
    <div class="rating-filter">
      <el-button 
        :type="selectedRating === null ? 'primary' : ''" 
        @click="filterByRating(null)"
        size="small"
      >
        全部
      </el-button>
      <el-button 
        v-for="rating in [5, 4, 3, 2, 1]" 
        :key="rating"
        :type="selectedRating === rating ? 'primary' : ''" 
        @click="filterByRating(rating)"
        size="small"
      >
        {{ rating }}星
      </el-button>
    </div>

    <!-- 评价列表 -->
    <div class="reviews-list" v-loading="loading">
      <div v-if="reviews.length === 0 && !loading" class="no-reviews">
        <p>暂无评价</p>
      </div>
      
      <div v-else class="review-item" v-for="review in reviews" :key="review.id">
        <div class="review-header">
          <div class="user-info">
            <el-avatar 
              :src="review.user?.avatarUrl" 
              :size="40"
            >
              {{ review.user?.nickname?.charAt(0) || '用' }}
            </el-avatar>
            <div class="user-details">
              <span class="username">{{ review.user?.nickname || '匿名用户' }}</span>
              <div class="review-rating">
                <el-rate 
                  v-model="review.rating" 
                  disabled 
                  size="small"
                />
                <span class="review-date">{{ formatDate(review.createdAt) }}</span>
              </div>
            </div>
          </div>
        </div>
        
        <div class="review-content">
          <p>{{ review.comment || '用户未留下评价内容' }}</p>
        </div>

        <!-- 商品信息 -->
        <div class="product-info" v-if="review.orderItem">
          <span class="product-name">{{ review.orderItem.productName }}</span>
          <span class="product-sku" v-if="review.orderItem.productSkuDesc">
            {{ review.orderItem.productSkuDesc }}
          </span>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination" v-if="total > pageSize">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

// 定义接口类型
interface User {
  id: number
  username: string
  nickname: string
  avatarUrl?: string
}

interface OrderItem {
  itemId: number
  productName: string
  productSkuDesc?: string
  productImage?: string
}

interface ProductReview {
  id: number
  orderItemId: number
  userId: number
  spuId: number
  skuId: number
  rating: number
  comment: string
  createdAt: string
  user?: User
  orderItem?: OrderItem
}

interface ReviewStatistics {
  totalReviews: number
  averageRating: number
  ratingDistribution: { [key: string]: number }
}

const props = defineProps<{
  productId?: number
}>()

// 响应式数据
const loading = ref(false)
const reviews = ref<ProductReview[]>([])
const statistics = ref<ReviewStatistics | null>(null)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const selectedRating = ref<number | null>(null)

// 获取评价列表
const fetchReviews = async () => {
  if (!props.productId) return
  
  loading.value = true
  try {
    const params = {
      productId: props.productId,
      page: currentPage.value,
      size: pageSize.value,
      rating: selectedRating.value,
      sortBy: 'createdAt',
      sortOrder: 'desc'
    }

    const response = await axios.get('/api/v1/review/list', { params })
    
    if (response.data.code === 200) {
      const data = response.data.data
      reviews.value = data.reviews || []
      total.value = data.total || 0
      
      // 如果是第一页，同时获取统计信息
      if (currentPage.value === 1) {
        await fetchStatistics()
      }
    } else {
      ElMessage.error(response.data.msg || '获取评价失败')
    }
  } catch (error) {
    console.error('获取评价失败:', error)
    ElMessage.error('获取评价失败')
  } finally {
    loading.value = false
  }
}

// 获取评价统计信息
const fetchStatistics = async () => {
  if (!props.productId) return
  
  try {
    const response = await axios.get('/api/v1/review/statistics', {
      params: { productId: props.productId }
    })
    
    if (response.data.code === 200) {
      statistics.value = response.data.data
    }
  } catch (error) {
    console.error('获取评价统计失败:', error)
  }
}

// 按评分筛选
const filterByRating = (rating: number | null) => {
  selectedRating.value = rating
  currentPage.value = 1
  fetchReviews()
}

// 分页处理
const handleSizeChange = (newSize: number) => {
  pageSize.value = newSize
  currentPage.value = 1
  fetchReviews()
}

const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage
  fetchReviews()
}

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'short',
    day: 'numeric'
  })
}

// 监听productId变化
watch(() => props.productId, () => {
  if (props.productId) {
    currentPage.value = 1
    selectedRating.value = null
    fetchReviews()
  }
}, { immediate: true })

// 组件挂载时获取数据
onMounted(() => {
  if (props.productId) {
    fetchReviews()
  }
})
</script>

<style scoped>
.product-reviews {
  margin-top: 20px;
}

.reviews-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.reviews-header h3 {
  margin: 0;
  color: #303133;
}

.reviews-stats {
  display: flex;
  align-items: center;
  gap: 20px;
}

.total-reviews {
  color: #606266;
  font-size: 14px;
}

.average-rating {
  display: flex;
  align-items: center;
}

.rating-filter {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.reviews-list {
  min-height: 200px;
}

.no-reviews {
  text-align: center;
  padding: 40px 20px;
  color: #909399;
}

.review-item {
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  margin-bottom: 15px;
  background: #fff;
}

.review-header {
  margin-bottom: 15px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-details {
  flex: 1;
}

.username {
  font-weight: 500;
  color: #303133;
  display: block;
  margin-bottom: 5px;
}

.review-rating {
  display: flex;
  align-items: center;
  gap: 10px;
}

.review-date {
  color: #909399;
  font-size: 12px;
}

.review-content {
  margin-bottom: 15px;
  line-height: 1.6;
  color: #606266;
}

.product-info {
  padding-top: 10px;
  border-top: 1px solid #f5f7fa;
  font-size: 12px;
  color: #909399;
}

.product-name {
  margin-right: 10px;
}

.product-sku {
  color: #c0c4cc;
}

.pagination {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

:deep(.el-rate) {
  --el-rate-icon-size: 16px;
}

:deep(.el-rate__text) {
  font-size: 12px;
}
</style>
